package com.cskaoyan.wordmemorize.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cskaoyan.wordmemorize.common.constant.ResultCodeEnum;
import com.cskaoyan.wordmemorize.common.exception.BusinessException;
import com.cskaoyan.wordmemorize.converter.EmployeeConverter;
import com.cskaoyan.wordmemorize.dao.entity.*;
import com.cskaoyan.wordmemorize.dao.mapper.*;
import com.cskaoyan.wordmemorize.dto.admin.DeleteEmployeeRoleOperateDTO;
import com.cskaoyan.wordmemorize.dto.admin.EmployeeDTO;
import com.cskaoyan.wordmemorize.dto.admin.PageDTO;
import com.cskaoyan.wordmemorize.request.EmployeeCommand;
import com.cskaoyan.wordmemorize.request.PageRequest;
import com.cskaoyan.wordmemorize.service.EmployeeService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.baomidou.mybatisplus.extension.toolkit.Db.getOne;

@Service
public class EmployeeServiceImpl  extends ServiceImpl<EmployeeMapper, EmployeeDO> implements EmployeeService{

    @Resource
    EmployeeMapper employeeMapper;
    @Resource
    EmployeeConverter employeeConverter;

    @Resource
    RoleMapper roleMapper;

    @Resource
    EmployeeRoleMapper employeeRoleMapper;

    @Resource
    RolePermissionMapper rolePermissionMapper;
    @Resource
    PermissionMapper permissionMapper;

    @Override
    public EmployeeDTO login(String userName, String password) {
        // 1. 查询数据库，验证后台用户的用户名和密码
        // 得到密文密码

        String passwd = SaSecureUtil.md5(password);

        LambdaQueryWrapper<EmployeeDO> employeeWrapper = new LambdaQueryWrapper<>();
        employeeWrapper.eq(EmployeeDO::getName, userName)
                .eq(EmployeeDO::getPassword, password);

        // 查询满足条件的员工
        EmployeeDO one = getOne(employeeWrapper);
        if (one == null) {
            System.out.println("没有该用户的信息");
            throw new BusinessException(ResultCodeEnum.LOCAL_LOGIN_FAIL);

        }

        return employeeConverter.employeeDO2DTO(one);
    }

    @Override
    public EmployeeDTO getEmployeeInfo(Long employeeId) {
        EmployeeDO employeeDO = employeeMapper.selectById(employeeId);
        if (employeeDO != null) {
            //设置权限集合
            employeeDO.setPerms(getPermissionAlias(employeeId));
            return employeeConverter.employeeDO2DTO(employeeDO);
        }
        return null;
    }


    //分页
    @Override
    public PageDTO<EmployeeDTO> getEmployeePage(PageRequest request) {
        Page<EmployeeDTO> page = new Page<>(request.getPageNum(), request.getCount());
        //获取数据
        List<EmployeeDO> list = employeeMapper.employeePage2DOs(page);
        //转化为DTO
        PageDTO<EmployeeDTO> pageDTO = employeeConverter.emoloyeePage2PageDTO(list, page.getTotal());
        return pageDTO;
    }

    @Override
    public void addEmployee(EmployeeCommand command) {
        EmployeeDO employeeDO = employeeConverter.command2EmployeeDO(command);
        //对密码进行加密
        employeeDO.setPassword(SaSecureUtil.md5(employeeDO.getPassword()));
        //放到employee_role表中
          //获取roleIds
        employeeDO.setRoleIds(stringListToLongList(command.getRoleIds()));
        // 插入到employee表中
        employeeMapper.insert(employeeDO);
        //遍历插入到 employee_role表中
         for (Long roleId : employeeDO.getRoleIds()) {
              EmployeeRoleDO employeeRoleDO = new EmployeeRoleDO();
              employeeRoleDO.setEmployeeId(employeeDO.getId());
              employeeRoleDO.setRoleId(roleId);
              employeeRoleMapper.insert(employeeRoleDO);
         }

    }

    private List<Long> stringListToLongList(List<String> roleIds) {
        List<Long> list = new ArrayList<>();
        for (String roleId : roleIds) {
            list.add(Long.parseLong(roleId));
        }
        return list;
    }

    @Override
    public void updateEmployee(EmployeeCommand command) {
        EmployeeDO employeeDO = employeeConverter.command2EmployeeDO(command);
        employeeMapper.updateById(employeeDO);
    }

    @Override
    public void delete(Long employeeId) {
        //逻辑删除
        employeeMapper.deleteEmployeeById(employeeId);
    }

    @Override
    public DeleteEmployeeRoleOperateDTO deleteRole(Long employeeId, Long roleId) {
        EmployeeDO employeeDO = employeeMapper.selectById(employeeId);
        RoleDO roleDO = roleMapper.selectById(roleId);
        DeleteEmployeeRoleOperateDTO deleteEmployeeRoleOperateDTO = employeeConverter.toDeleteEmployeeRoleOperateDTO(employeeDO, roleDO);
        return null;
    }

    @Override
    public void updateLoginInfo(Long employeeId, String ip, LocalDateTime time) {
        employeeMapper.updateLoginInfo(employeeId, ip, time);
    }

    @Override
    public List<String> getPermissionAlias(Long employeeId) {
        // permission_code集合
        List<String> perms = new ArrayList<>();
        //在employee_role中获取当前对象的role-id
          //建造条件构造器
        LambdaQueryWrapper<EmployeeRoleDO> employeeRoleWrapper = new LambdaQueryWrapper<>();
        employeeRoleWrapper.eq(EmployeeRoleDO::getEmployeeId, employeeId);
        //从employee_role中获取role_id
        EmployeeRoleDO employeeRoleDO = employeeRoleMapper.selectOne(employeeRoleWrapper);
        if (employeeRoleDO.getRoleId() != null) {
            //根据role-id在role_permission中获取permission-id（多个）
            LambdaQueryWrapper<RolePermissionDO> rolePermissionWrapper = new LambdaQueryWrapper<>();
            rolePermissionWrapper.eq(RolePermissionDO::getRoleId, employeeRoleDO.getRoleId());
            List<RolePermissionDO> rolePermissionDOS = rolePermissionMapper.selectList(rolePermissionWrapper);
            //遍历rolePermissionDOS获取permission_id然后在permission中获取permission_code放入集合中（一对一关系）
            for (RolePermissionDO rolePermissionDO : rolePermissionDOS) {
                //通过permission的id（即role_permission里的permission_id）获取
                 PermissionDO rolePermissionDO1 = permissionMapper.selectById(rolePermissionDO.getPermissionId());
                 //判断存在，若存在则放入集合中
                if (rolePermissionDO1 != null) {
                    perms.add(rolePermissionDO1.getPermissionCode());
                }
            }
        }
//        //转化为Set
//        Set<String> setPerms = new HashSet<>(perms);
        return perms;
    }
}
